package org.wattdepot.cli.command;


import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Prints the power generated (or consumed) by the source at the given timestamp.
 * 
 * 
 * @author Alex Kan and Kelvin Green
 * @version 2.0
 */
public class WattDepotListPowerCommand extends WattDepotCommand {
  /**
   * Prints the power generated (or consumed) by the source at the given timestamp.
   * 
   * @param args contains an array of strings created from the user input.
   * @return a string containing the power requested.
   */
  public String doCommand(String args[]) {
    
    if (0 != args[3].compareTo("timestamp") || args.length != 5) {
      return "power [generated|consumed] {source} timestamp {timestamp}";
    }
    return getPower(args);
  }
  
  /**
   * Get the power generated (or consumed) by the source at the given timestamp.
   * 
   * @param args contains an array of strings created from the user input.
   * @return a string variable named output containing all the output for the method.
   */
  private String getPower(String[] args) {
    String output = ""; // Holds the output that will be returned at the end of the method.
    boolean error = false; // Is set to true when an error occurs.
    try {

      XMLGregorianCalendar tstamp = null;
      try {
        tstamp = Tstamp.makeTimestamp(args[4]);
      }
      catch (Exception e) {
        return "Timestamp is not properly formatted.";
      }
      if (0 == args[1].compareTo("consumed")) {
        double powerValue = getClient().getPowerConsumed(args[2], tstamp) / 1000000;
        output += powerValue + cr;
      }
      else if (0 == args[1].compareTo("generated")) {
        double powerValue = getClient().getPowerGenerated(args[2], tstamp) / 1000000;
        output += powerValue + cr;
      }
      else {
        return BAD_FORMAT;
      }
    }
    catch (MiscClientException mce) {
      return CON_NOT_FOUND;
    }
    catch (NotAuthorizedException nae) {
      error = true;
      if (error) {
        return "Application Error.";
      }
    }
    catch (ResourceNotFoundException rne) {
      return RES_NOT_FOUND;
    }
    catch (BadXmlException bxe) {
      error = true;
    }
    catch (Exception e) {
      error = true;
    }

    return output;
  }

}
